package com.kye.express.business.jd.goods_detail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.jd.address.JDAddressListActivity;
import com.kye.express.business.verification.ExchangeVerificationService;
import com.kye.express.databinding.ActivityJdgoodsExchangeBinding;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.jd.address.JDAddressBean;
import com.kye.model.bean.jd.goods_detail.JDCheckGoodsAvailableResultBean;
import com.kye.model.bean.jd.order_details.request.RequestGooodsExchange;
import com.kye.model.bean.user.User;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 京东订单详情需要监听结果返回，更新地址操作的结果
 */
public class JDGoodsExchangeActivity extends BaseAppCompatActivity implements JDGoodsExchangeContract.JDGoodsExchangeView, ExchangeVerificationService.OnVerificationCheckListener, ExchangeVerificationService.OnVerificationOptionByAutoSendListener, ExchangeVerificationService.OnVerificationOptionByPictureSmsListener {

    private final static String TAG_SELECTED_ADDRESS = "TAG_SELECTED_ADDRESS";
    private final static String TAG_GOODS_AVAILABLE = "TAG_GOODS_AVAILABLE";
    private final static String TAG_REQUEST_PARAM = "TAG_REQUEST_PARAM";
    private final static String TAG_SELECTED_ADDRESS_LIST = "TAG_SELECTED_ADDRESS_LIST";
    public final static int REQUEST_CODE_ADDRESS = 3000;
    public final static int RESULT_CODE_ADDRESS_SELECT = JDAddressListActivity.RESULT_CODE_ADDRESS_SELECT; // 选择了地址
    public final static int RESULT_CODE_ADDRESS_UPDATE = JDAddressListActivity.RESULT_CODE_ADDRESS_UPDATE; // 更新了地址（删除，编辑，新增)
    private JDGoodsExchangeContract.JDGoodsExchangePresenter presenter;
    private ActivityJdgoodsExchangeBinding binding;
    private JDAddressBean selectedAddress;
    private RequestGooodsExchange requestGooodsExchange;
    private List<JDAddressBean> addressList = new ArrayList<>();
    private int resultCode = Activity.RESULT_CANCELED;
    private User userInfo;
    private ExchangeVerificationService exchangeVerificationService;
    private Dialog dialog;
    private JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean;
    private MaterialDialog showWarningDialog;

    public static void startActivity(Activity activity, int requestCode, JDAddressBean selectedAddress, JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean, RequestGooodsExchange requestGooodsExchange) {
        Intent intent = new Intent(activity, JDGoodsExchangeActivity.class);
        intent.putExtra(TAG_SELECTED_ADDRESS, selectedAddress);
        intent.putExtra(TAG_REQUEST_PARAM, requestGooodsExchange);
        intent.putExtra(TAG_GOODS_AVAILABLE, jdCheckGoodsAvailableResultBean);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            selectedAddress = getIntent().getParcelableExtra(TAG_SELECTED_ADDRESS);
            jdCheckGoodsAvailableResultBean = getIntent().getParcelableExtra(TAG_GOODS_AVAILABLE);
            requestGooodsExchange = getIntent().getParcelableExtra(TAG_REQUEST_PARAM);
        } else {
            selectedAddress = savedInstanceState.getParcelable(TAG_SELECTED_ADDRESS);
            jdCheckGoodsAvailableResultBean = savedInstanceState.getParcelable(TAG_GOODS_AVAILABLE);
            requestGooodsExchange = savedInstanceState.getParcelable(TAG_REQUEST_PARAM);
            addressList = savedInstanceState.getParcelableArrayList(TAG_SELECTED_ADDRESS_LIST);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_jdgoods_exchange);
        presenter = new JDGoodsExchangeContract.JDGoodsExchangePresenter();
        initToolbar(savedInstanceState);
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelable(TAG_SELECTED_ADDRESS, selectedAddress);
        outState.putParcelable(TAG_REQUEST_PARAM, requestGooodsExchange);
        outState.putParcelable(TAG_GOODS_AVAILABLE, jdCheckGoodsAvailableResultBean);
        outState.putParcelableArrayList(TAG_SELECTED_ADDRESS_LIST, (ArrayList<JDAddressBean>) addressList);
        super.onSaveInstanceState(outState);
    }

    private void initToolbar(Bundle savedInstanceState) {
        ToolbarManager.setToolbar(this, binding.toolbar);
    }

    private void initViews(Bundle savedInstanceState) {

    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.address)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        JDAddressListActivity.startActivity(JDGoodsExchangeActivity.this, REQUEST_CODE_ADDRESS, selectedAddress);
                    }
                });
        RxView.clicks(binding.addressNoAddress)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        JDAddressListActivity.startActivity(JDGoodsExchangeActivity.this, REQUEST_CODE_ADDRESS, selectedAddress);
                    }
                });
        RxView.clicks(binding.makeOrder)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (selectedAddress == null) {
                            ToastManager.show(JDGoodsExchangeActivity.this, "请输入邮箱号码");
                            return;
                        }
                        if (!jdCheckGoodsAvailableResultBean.isCancelable()) {
                            showWarningDialog();
                        } else {
                            exchangeVerificationService.check(JDGoodsExchangeActivity.this);
                        }
                    }
                });
        RxTextView.textChanges(binding.email)
                .compose(bindToLifecycleDestroy())
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        String email = charSequence.toString();
                        requestGooodsExchange.setEmail(email);
                    }
                });
    }

    private void showWarningDialog() {
        showWarningDialog = new MaterialDialog.Builder(JDGoodsExchangeActivity.this)
                    .content("确认兑换?")
                    .positiveText("确认")
                    .positiveColor(getResources().getColor(R.color.purple_0))
                    .negativeText("取消")
                    .negativeColor(getResources().getColor(R.color.black_666))
                    .backgroundColor(getResources().getColor(R.color.window_background))
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            exchangeVerificationService.check(JDGoodsExchangeActivity.this);
                        }
                    })
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        }
                    })
                    .show();
    }

    private void initData(Bundle savedInstanceState) {
        /**
         * 默认返回结果, 商品详情不更新
         */
        setResult(resultCode, new Intent());
        binding.setData(selectedAddress);
        binding.setGoodsAvailable(jdCheckGoodsAvailableResultBean);
        presenter.bind(this);
    }

    @Override
    public void onUser(User user) {
        this.userInfo = user;
        exchangeVerificationService = new ExchangeVerificationService(user.getPhone(), 1);
        exchangeVerificationService.setProvider(getProvider());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * todo : 处理地址管理的操作结果
         */
        if (requestCode == REQUEST_CODE_ADDRESS) {
            JDAddressBean addressBean = data.getParcelableExtra("data");
            List<JDAddressBean> addressBeanList = data.getParcelableArrayListExtra("datas");
            Logger.d("addressBean : " + GsonUtils.toJsonString(addressBean, true));
            Logger.d("addressBeanList : " + GsonUtils.toJsonString(addressBeanList, true));
            if (addressBeanList == null) {
                addressBeanList = new ArrayList<>();
            }
            switch (resultCode) {
                case JDAddressListActivity.RESULT_CODE_ADDRESS_SELECT:
                    // 选中了地址返回，设置为默认的地址,并且刷新判断是否有货
                case JDAddressListActivity.RESULT_CODE_ADDRESS_UPDATE:
                    // 需要重新刷新地址列表,如果有地址返回初始化返回的地址为默认,并且判断是否有货
                    // todo : 地址管理返回可能删除了详情选中的地址
                    this.resultCode = resultCode;
                    selectedAddress = addressBean;
                    addressList = addressBeanList;
                    Intent intent = new Intent();
                    intent.putExtra("data", selectedAddress);
                    intent.putParcelableArrayListExtra("datas", (ArrayList<JDAddressBean>) addressList);
                    setResult(resultCode, intent);
                    updateExchangeAddress(userInfo, selectedAddress, addressList);
                    break;
                case Activity.RESULT_CANCELED:
                    Logger.d("address nothing");
                    break;
            }
        }
    }

    private void updateExchangeAddress(User userInfo, JDAddressBean selectedAddress, List<JDAddressBean> addressList) {
        binding.setData(selectedAddress);
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(this, dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }


    @Override
    public void onCannotExchangeError(String msg) {
        /**
         * todo : 跳转到人气支持
         */
        ToastManager.show(this, msg);
    }

    @Override
    public void onNeedSendSmsError(String msg, String smsChannel, String type, String phone) {
        exchangeVerificationService.showVerificationByAutoSendMessage(this, 2, phone, smsChannel, this);
    }

    @Override
    public void onAccountError(String msg, String smsChannel, String type, String phone) {

    }

    @Override
    public void onOpenApiError(OpenApiResult openApiResult) {

    }

    @Override
    public void onOtherError(Throwable e) {

    }

    @Override
    public void onVerifyByAutoSendMessage(String smsChannel, String type, String phone) {
        exchangeVerificationService.showVerificationByAutoSendMessage(this, 2, phone, smsChannel, this);
    }

    @Override
    public void onVerifyByPictureSms(String smsChannel, String type, String phone) {
        exchangeVerificationService.showVerificationByPictureSmsDialog(this, 2, this);
    }

    @Override
    public void getPictureCodeSuccess(byte[] picture) {

    }

    @Override
    public void onSendSmsCodeSuccess() {

    }

    /**
     * 动态吗，验证码验证
     */
    @Override
    public void toExchange1(String smsCodeInput, MaterialDialog mDialog) {
        presenter.exchange(requestGooodsExchange, smsCodeInput, mDialog);
    }

    /**
     * 发送短信验证
     * @param smsCodeInput
     * @param mDialog
     */
    @Override
    public void toExchange2(String smsCodeInput, MaterialDialog mDialog) {
        presenter.exchange(requestGooodsExchange, smsCodeInput, mDialog);
    }

    @Override
    public void exchangeSuccess(MaterialDialog dialog) {
        dialog.dismiss();
        resultCode = Activity.RESULT_OK;
        setResult(resultCode, new Intent());
        ToastManager.show(this, "兑换成功");
        finish();
    }

    @Override
    public void exchangeFailed(MaterialDialog dialog, String msg) {
        ToastManager.show(this, msg);
    }
}
